/**
 * Return signed random integer from given range
 * rand(25); equals rand(0, 25);
 * @param min Number
 * @param [max] Number
 */
function rand( min, max ) { return max ? Math.floor(Math.random() * (max - min + 1)) + min : Math.floor(Math.random() * (min + 1));}
Array.prototype.random = function(){ return this[rand(this.length-1)]};

/**
 * Cell
 */
function CellClass(x, y, dom, appMap){
	this.dom = dom;
	this.x = x;
	this.y = y;
    this.color = app.colors.random();
	this.changedOnStep = 0;
    this.appMap = appMap;
}

/**
 * Change color
 */
CellClass.prototype.changeColor = function(color, depth, step){
    depth = depth || 0;
	
	if(this.changedOnStep == step)
        return;
	this.changedOnStep = step;
    if(depth > 0)
    {
        for(var i=0; i<4; i++){
            var cell = this.getNeighborCell(i);
            if(cell){
                if(cell.color == this.color || cell.color == color)
                    cell.changeColor(color, depth, step);
            }
        }
    }
	this.setColor(color);
	app.cellsInRegion++;
};

/**
 * SetColor
 */
CellClass.prototype.setColor = function(color){
	this.color = color;
	this.dom.style.backgroundColor = this.color;
};

/**
 * GetNeighbourCell
 */
CellClass.prototype.getNeighborCell = function(n){
    var map = [{x:-1, y:0}, {x:0, y:-1}, {x:1,y:0}, {x:0,y:1}];
    var x = this.x + map[n].x;
    var y = this.y + map[n].y;
    if((x < 0)|| x > this.appMap.cols - 1) return null;
    if((y < 0)|| y > this.appMap.rows - 1) return null;
    return this.appMap.getCell(x, y);//[x][y];
};